<template>
  <el-card class="mb-2.5" v-show="SearchShow">
    <!-- 搜索表单 -->
    <el-form ref="searchFormRef" :model="searchForm" label-position="left">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="用户ID/用户昵称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" :icon="Search" plain @click="handleSearch">搜索</el-button>
          <el-button :icon="RefreshRight" @click="handleSearchFormReset">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card>
    <!-- 数据表格 -->
    <div class="table-container">
      <div class="mb-2.5">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button type="primary" :icon="CirclePlus" @click="openDialogForm(true)">新增提现申请</el-button>
          </el-col>
          <el-col :span="12">
            <div class="flex justify-end">
              <el-button :icon="Search" circle @click="SearchShow = !SearchShow"/>
              <el-button :icon="RefreshRight" circle @click="handleSearchFormReset"></el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%;">
          <el-table-column align="center" prop="id" label="ID"></el-table-column>
          <el-table-column align="center" prop="order_no" label="订单号"></el-table-column>
          <el-table-column align="center" prop="user_id" label="用户ID"></el-table-column>
          <el-table-column align="center" prop="nickname" label="用户昵称"></el-table-column>
          <el-table-column align="center" prop="open_id" label="openID"></el-table-column>
          <el-table-column align="center" prop="amount" label="提现金额"></el-table-column>
          <el-table-column align="center" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusInfo(scope.row.status).type">
                {{ getStatusInfo(scope.row.status).text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="apply_time" label="申请时间"></el-table-column>
          <el-table-column align="center" prop="process_time" label="处理时间"></el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="openDialogForm(false, scope.row)">审核</el-button>
              <!--              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="py-5 px-0 flex justify-end">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[15, 30, 50, 100]"
                       :disabled="false" background layout="total, sizes, prev, pager, next, jumper"
                       :total="total"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-dialog v-model="formShow" :title="dialogTitle" width="700">
      <el-form ref="formDataRef" class="pa-5" :rules="rules" :model="formData" label-position="right"
               label-width="auto">
        <el-form-item label="提现金额">
          <el-input v-model="formData.amount" placeholder="请输入提现金额" autocomplete="off"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="订单号" prop="order_no">
              <el-input v-model="formData.order_no" placeholder="请输入订单号" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户ID" prop="user_id">
              <el-input v-model="formData.user_id" placeholder="请输入用户ID" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="0">待审核</el-radio>
                <el-radio :value="1">已通过</el-radio>
                <el-radio :value="2">已拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="处理备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入处理备注" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, computed, nextTick} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import {RefreshRight, Search, CirclePlus} from '@element-plus/icons-vue'
import {getWithdrawalApplyList, getWithdrawalApplyInfo, saveWithdrawalApplyInfo, updateWithdrawalApplyInfo, deleteWithdrawalApply} from '@/api/withdrawal'

// 表格数据
const tableData = ref([]);
// 表格数据总数量
const total = ref(0);
// 当前分页
const currentPage = ref(1);
// 项目条数
const pageSize = ref(15);
// 是否显示搜索表单视图
const SearchShow = ref(true);
// 表单对话框
const formShow = ref(false);
// 对话框标题
const dialogTitle = computed(() => (isAdd.value ? '新增提现申请' : '审核提现申请'));
// 提交表单ref
const formDataRef = ref<FormInstance>();
// 搜索表单ref
const searchFormRef = ref<FormInstance>();
// 是否新增
const isAdd = ref(false);

// 定义搜索表单的接口类型
interface SearchFormTypes {
  keyword?: string;
}

// 使用 reactive 初始化 searchForm，并提供默认值
const searchForm = ref<SearchFormTypes>({});

// 接口类型
interface FormDataTypes {
  id?: number
  order_no: string
  user_id: string
  amount: string
  status: number
  remark: string
  apply_time?: string
  process_time?: string
  open_id?: string
  nickname?: string
}

// 表单数据字段
const initForm = reactive<FormDataTypes>({
  order_no: '',
  user_id: '',
  amount: '',
  status: 0,
  remark: ''
})

// 表单数据字段
const formData = reactive<FormDataTypes>({...initForm})

const rules = ref<FormRules<FormDataTypes>>({
  order_no: [
    {required: true, message: '订单号必填', trigger: 'change'},
  ],
  user_id: [
    {required: true, message: '用户ID必填', trigger: 'change'},
  ],
  amount: [
    {required: true, message: '提现金额必填', trigger: 'change'},
  ]
  // force_update 字段是非必需的，不需要验证规则
});

// 状态标签
const statusMap = {
  0: { type: 'info', text: '待审核' },
  1: { type: 'primary', text: '已通过' },
  2: { type: 'danger', text: '已拒绝' }
} as const;

const getStatusInfo = (status: number) => statusMap[status] || { type: 'info', text: '未知状态' };

// 加载表格数据
const loadTableData = async (params: { page?: number; page_size?: number } = {}) => {
  const response = await getWithdrawalApplyList({
    ...params, // 动态传递分页参数或搜索条件
    ...searchForm.value, // 拼接搜索条件
  });
  tableData.value = response.data.list;
  total.value = response.data.total;
};

// 搜索逻辑
const handleSearch = () => {
  currentPage.value = 1; // 搜索后重置到第一页
  loadTableData({ page: currentPage.value, page_size: pageSize.value }); // 调用加载方法并传递分页参数
};

// 重置搜索表单
const handleSearchFormReset = () => {
  searchForm.value = {};
  currentPage.value = 1; // 重置后也回到第一页
  loadTableData({ page: currentPage.value, page_size: pageSize.value }); // 重新加载初始数据
};

// 删除行数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除此提现申请吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then( async () => {
    // 执行删除操作
    await deleteWithdrawalApply(row.id);
    // 刷新表格数据
    await loadTableData({ page: currentPage.value, page_size: pageSize.value });
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 表格行数变化处理
const handleSizeChange = async (page: number) => {
  pageSize.value = page;
  await loadTableData({page: currentPage.value, page_size: pageSize.value})
}

// 分页变化处理
const handleCurrentChange = async (newPage) => {
  currentPage.value = newPage;
  await loadTableData({page: currentPage.value, page_size: pageSize.value})
};

// 打开对话表单
const openDialogForm = async (isNew: boolean, row?: {id: number}) => {
  formShow.value = true; // 显示对话框
  isAdd.value = isNew;

  Object.assign(formData, initForm);
  delete formData.id;
  await nextTick(() => {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  });

  if (!isAdd.value) {
    // 编辑时获取提现申请信息
    const response = await getWithdrawalApplyInfo(row.id);
    Object.assign(formData, response.data); // 将接口数据合并到 formData 中
  }
};

// 关闭对话表单
const handleClose = () => {
  formShow.value = false;
}

// 提交应用版本表单
const handleSubmit = async () => {
  if (!formDataRef.value) return;

  // 校验表单
  await formDataRef.value.validate();

  // 判断是否为新增或更新
  const isUpdate = !!formData.id; // 如果存在 id，则为更新操作

  // 执行新增或更新操作
  if (isUpdate) {
    // 更新操作
    await updateWithdrawalApplyInfo(formData.id, formData);
    ElMessage.success('审核成功');
  } else {
    // 新增操作
    await saveWithdrawalApplyInfo(formData);
    ElMessage.success('新增成功');
  }

  // 关闭对话框并刷新表格数据
  handleClose();
  await loadTableData({page: currentPage.value, page_size: pageSize.value});
};

onMounted(() => {
  loadTableData(); // 在组件挂载后加载数据
});
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-wrapper {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}
</style>